package com.mindbook.testredis.service;

import ch.qos.logback.core.util.TimeUtil;
import com.sun.jndi.ldap.Connection;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import java.util.Collection;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;


@Component
public class RedisService {

    @Autowired private RedisTemplate<String,Object> redisTemplate;

    //默认过期时间长度: 1Day
    private static final long DEFAULT_EXPIRE = 60*60*24;

    //是否存在与key值对应的数据
    public boolean existsKey(String key){
        return redisTemplate.hasKey(key);
    }

    //重置key
    public void renameKey(String oldKey,String newKey){
        redisTemplate.rename(oldKey, newKey);
    }

    //删除key的集合
    public void deleteKey(Collection<String> keys){
        Collection<String> kSet = keys.stream().map(k -> k).collect(Collectors.toSet());
        redisTemplate.delete(kSet);
    }

    /**
     * 设置key的生命周期
     * @param key
     * @param time
     * @param timeUnit
     */
    public void expireKey(String key, long time, TimeUnit timeUnit){
        redisTemplate.expire(key,time,timeUnit);
    }

    /**
     * 查询key的生命周期
     * @param key
     * @param timeUnit
     * @return
     */
    public long getKeyExpire(String key,TimeUnit timeUnit){
        return redisTemplate.getExpire(key,timeUnit);
    }

    /**
     * 将key设置为永久失效
     * @param key
     */
    public void persistKey(String key){
        redisTemplate.persist(key);
    }

}
